/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { CommonConst } from '../../../../src/const/common-const.js';
import { initExecuteCommand, runHvigorFailAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    /**
     * 执行打包的 har 模块
     */
    baseHar: {
      runtimeOS: RuntimeOSType.HarmonyOS,
      apiVersion: APIVersion.API11,
      apiType: APIType.STAGE,
      language: LanguageType.ArkTs,
      abilityType: AbilityType.Application,
      moduleTemplateType: ModuleTemplateType.StaticLibrary,
    },
    /**
     * 被 baseHar 依赖的模块，版本号为默认的 1.0.0
     */
    har1:{
      runtimeOS: RuntimeOSType.HarmonyOS,
      apiVersion: APIVersion.API11,
      apiType: APIType.STAGE,
      language: LanguageType.ArkTs,
      abilityType: AbilityType.Application,
      moduleTemplateType: ModuleTemplateType.StaticLibrary,
    },
  },
};

const testCaseFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  // 创建 parameterFile.json5
  fse.writeFileSync(
    path.resolve(projectRootPath, 'parameterFile.json5'),
    JSON.stringify({
      version: {
        base: '1.0.1',
      },
      dep: {
        har1: './haR1', // 实际目录名是 har1，parameterFile 要求大小写敏感，大小写路径不匹配时视为不存在
        notExist: 'file:./notExist', // 不存在的本地依赖目录，确保抛出预期的报错
      }
    }),
  );

  // 在工程级 oh-package.json5 新增 parameterFile 属性
  const projectOhPackageJsonPath = path.resolve(projectRootPath, CommonConst.OH_PACKAGE_JSON5);
  const projectOhPackageJson = fse.readJsonSync(projectOhPackageJsonPath);
  projectOhPackageJson.parameterFile = './parameterFile.json5';
  fse.writeJsonSync(projectOhPackageJsonPath, projectOhPackageJson);

  // 测试本地依赖路径大小写不匹配的场景
  const ohPackageJsonPath = path.resolve(projectRootPath, 'baseHar', CommonConst.OH_PACKAGE_JSON5);
  const ohPackageJson = fse.readJsonSync(ohPackageJsonPath);
  fse.writeJsonSync(ohPackageJsonPath, {
    ...ohPackageJson,
    dependencies: {
      har1: '@param:dep.har1',
    },
  });
  const assembleHarResult = await runHvigorFailAsync(
    projectRootPath,
    initExecuteCommand({
      mode: 'module',
      product: 'default',
      module: 'baseHar@default',
      tasks: 'assembleHar',
    }),
  );
  expect(assembleHarResult.stderr).toContain('Local dependency in parameterFile does not exist');

  // 测试本地依赖路径不存在的场景
  fse.writeJsonSync(ohPackageJsonPath, {
    ...ohPackageJson,
    dependencies: {
      notExist: '@param:dep.notExist',
    },
  });
  const notExistResult = await runHvigorFailAsync(
    projectRootPath,
    initExecuteCommand({
      mode: 'module',
      product: 'default',
      module: 'baseHar@default',
      tasks: 'assembleHar',
    }),
  );
  expect(notExistResult.stderr).toContain('Local dependency in parameterFile does not exist');
};

TestCaseBuilder.builder()
  .caseName('parameterFile_error.test.ts')
  .description('本地依赖参数化异常场景')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.AR).ohpmInstall(IsEnable.Enable).build())
  .testFun(testCaseFun)
  .load();
